var express = require('express')
//上传图片必备中间件及文件夹
const fs = require('fs')
const multer = require('multer')
// const upload = multer({ dest: './uploads' })

var router = express.Router()

//图片上传
var stroage = multer.diskStorage({
  //设置上传的文件夹
  destination: function (req, file, cd) {
    cd(null, './uploads') // 注意是根目录 ，根目录，根目录
  },
  filename: function (req, file, cb) {
    //设置图片的名称
    cb(null, `${Date.now()}-${file.originalname}`)
  },
})
var upload = multer({ storage: stroage })
//upload.any()
router.post('/upload', upload.any(), (req, res, next) => {
  /*注意  app.js中设置(*设置token后，放在expressJwt 前面  ，在它可能图片不显示*)
   ***  app.use(express.static(path.join(__dirname, 'public')));
   ***  设置托管静态目录; 项目根目录+ public.  可直接访问public文件下的文件eg:http://localhost:3000/images/url.jpg
   */

  //拼接ulr 地址，本地监听的端口和图片的目录；
  // console.log(req.files)
  let url = `http://${req.headers.host}/uploads/${req.files[0].filename}`
  if (!req.files) {
    return res.json({
      code: 1,
      message: '上传失败',
    })
  } else {
    return res.json({
      code: 200,
      message: '上传成功',
      url: url,
    })
  }
})

// 编辑器图片上传
router.post('/uploads', upload.any(), (req, res) => {
  // console.log(req.headers)
  // console.log(req.files)
  let url = `http://${req.headers.host}/uploads/${req.files[0].filename}`
  console.log(url)

  res.send({
    errno: 0,
    data: [
      {
        code: 200,
        url: url,
        // imgPath: req.file.path, //文件存储的路径
        // imgName: req.file.filename,
      },
    ],
  })
})

router.post('/delete', upload.any(), function (req, res, next) {
  console.log(req.body)
  // {
  //   url: 'http://localhost:3000/uploads/1656664477623-Snipaste_2022-06-27_16-50-44.jpg'
  // }
  var url
  var path
  url = req.body.url

  sendUrl = url.indexOf('uploads') //用到js截取，以public截取点
  console.log(sendUrl)
  // 起始索引22
  console.log(url.length)
  // 结束索引76
  path = url.substring(sendUrl, url.length) //取后部分包括uploads
  console.log(path)
  // uploads/1656664477623-Snipaste_2022-06-27_16-50-44.jpg
  fs.unlink(path, (err) => {
    if (err) throw err
    res.json({ message: '图像已删除' })
  })
})
module.exports = router
